//发送请求
var g_wait_time = 2000;

function api_medicare_send_request(content, respond_url) {
    try {
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        if (fso.FileExists("D:\\ybjk\\sfjk\\reply.txt")) {
            //TODO:测试环境下
            //alert("删除文件");

            //TODO:正式环境下，需要取消该行的注释
            //fso.DeleteFile("D:\\ybjk\\sfjk\\reply.txt", true);
            var file = fso.GetFile("D:\\ybjk\\sfjk\\reply.txt");
			file.Delete(true);
        }

        //打开请求文件
        if (!fso.FileExists("D:\\ybjk\\sfjk\\request.txt")) {
            fso.CreateTextFile("D:\\ybjk\\sfjk\\request.txt", true);
        }

        //打开请求文件，写入请求数据
        var request_file = fso.OpenTextFile("D:\\ybjk\\sfjk\\request.txt", 2);
        request_file.write(content);
        request_file.Close();
        window.setTimeout("api_medicare_get_reply(2000,'" + respond_url + "')", g_wait_time);
        alert("正在获取信息，请稍等");
        
    } catch (e) {
        alert(e.message);
    }
}

//获取响应数据
function api_medicare_get_reply(time_wait, respond_url) {
    try {
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        
        try
        {
        	var f = fso.OpenTextFile("D:\\ybjk\\sfjk\\reply.txt", 1);
        }
        catch(err)
        {
        	alert("文件还未准备好");
        	 if (parseInt(time_wait) > 12000) 
        	 {
                alert("响应超时:请重新操作");
             } 
             else 
             {
                    var new_time = parseInt(time_wait) + g_wait_time + "";
                    window.setTimeout("api_medicare_get_reply(" + new_time + ",'" + respond_url + "')", g_wait_time);
                    alert("响应中:请耐心等待..."); 
                
            }
            return ;
        }
        
        { 
          //判断响应文件不存在的情况下，继续等待
            var f = fso.OpenTextFile("D:\\ybjk\\sfjk\\reply.txt", 1);
 			var content = f.ReadAll();
            f.Close();
           
           
            var json_obj = file_content_process(content);
            if (json_obj.code == 0) {
                alert(json_obj.msg);
                return;
            }

            var param = { content: content };
            if($("#csrf").length > 0)
            {//添加CSRF认证字符串
                var csrf_key = $("#csrf").attr("name");
                param[csrf_key] = $('#csrf').val();
            }

            // alert(JSON.stringify(param));

            $.post(respond_url, param, function(respond) {
                eval("respond=" + respond);

                if (respond.code == 0) {
                    alert(respond.msg);
                    return;
                }

                if (typeof(respond) != undefined) {
                    if (respond.exe_func != "") {
                        fun_callback(eval(respond.exe_func), [respond.param]);
                    }
                } else {
                    alert(respond.msg);
                }
            });
        }
    } catch (e) {
        alert(e.message);
    }
}

///读卡填充界面
function register_readcard_callback(param) {
    $('#username').val(param.username);
    $('#gender').val(param.gender);
    $('#age').val(param.age);
    $('#birthday').val(param.birthday);
    $('#sb_card_id').val(param.cardno);
    $('#csrf').val(param.csrf);
}


//
function register_cancel_readcard_callback(param) {
    if(param.medical_barcode != "")
    {
        $('#medical_barcode').val(param.medical_barcode);
    }

    if(param.cardno != "")
    {
        $('#sb_card_id').val(param.cardno);
    }

    //缓存未处理的单据号
    $('#rec_code').val(param.rec_codes);
    $("#csrf").val(param.csrf);
}


//体检项目补开回调函数
function checkitem_add_callback(param)
{
    if(param.cardno != "")
    {
        $('#sb_card_id').val(param.cardno);
    }
    if(param.pc_id != "")
    {
        $('#pc_id').val(param.pc_id);
    }
    $("#csrf").val(param.csrf);
}



//体检登记回调函数
function register_callback() {
    document.getElementById('form1').submit();
}

//体检登记冲销回调函数
function register_cancel_callback(param) 
{
    alert("登记冲销成功");
    $("#csrf").val(param.csrf);
    $('#btn_register_cancel').removeClass("disabled");
    $('#btn_register_cancel').html("登记冲销");
}

//体检收费读卡回调函数
function recharge_readcard_callback(param) {
    //充值读卡成功时，将读取的卡号填充到页面输入框
    $('#sb_card_id').val(param.cardno);
    $('#tjlsh0').val(param.tjlsh0);
    $('#csrf').val(param.csrf);
}

//体检收费确认并传送明细回调函数
function recharge_send_detail_callback(param)
{
    $('#csrf').val(param.csrf);
    if(param.code == 1)
    {//医保接口交互成功时，调用体检系统的后台处理事件
        query_process();
        $('#confirm_cancel').removeClass("disabled");
        $('#confirm_cancel').html("提交支付");
    }
    else
    {//医保接口调用不成功时，弹出提示信息
        alert(param.msg);
    }
}

//收费冲销处理结果的返回处理
function recharge_canceled_send_detail_callback(param)
{
    $('#csrf').val(param.csrf);
    $('#batch_left_num').val(parseInt($('#batch_left_num').val())-1);

    if(parseInt($('#batch_left_num').val()) == 0)
    {
        alert("处理完成");
        query_process();
        $('#confirm_cancel').removeClass("disabled");
        $('#confirm_cancel').html("提交退账");
    }
}


//文件解析
function file_parse(content) {
    var data = {};
    var arr = content.split("\r\n");
    if (arr.length > 0) {
        for (var i = 1; i < arr.length; i++) {
            var buf = arr[i].split("=");
            if (buf.length > 1) {
                data[buf[0]] = buf[1];
            }
        }
    }
    return data;
}

//响应内容处理
function file_content_process(content) {
    try {
        var data = file_parse(content);
        if (data) {
            if (data['reply'] == "FALSE") {
                return { code: 0, msg: "文件响应失败" };
            } else {
                if (data['success'] == "FALSE") {
                    return { code: 0, msg: data['error'] };
                } else {
                    return { code: 1, msg: "" };
                }
            }
        } else {
            return { code: 0, msg: "文件解析失败" };
        }
    } catch (e) {
        alert(e.message);
    }
}

//发送请求
function medicare_test_reply(content) {
    try {
        var fso = new ActiveXObject("Scripting.FileSystemObject");

        if (!fso.FileExists("D:\\ybjk\\sfjk\\reply.txt")) {
            fso.CreateTextFile("D:\\ybjk\\sfjk\\reply.txt", true);
        }

        var request_file = fso.OpenTextFile("D:\\ybjk\\sfjk\\reply.txt", 2);
        request_file.write(content);
        request_file.Close();
    } catch (e) {
        alert(e.message);
    }
}


//动态调用函数
function fun_callback(fn, args) {
    fn.apply(this, args);
}

//=======================================================
//发送读卡请求
function medicare_send_request_readcrad(param) {
    var content_arr = new Array();
    content_arr.push("[tjdjsk]");
    content_arr.push("request=TRUE");
    //
    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}

//发送登记请求
function medicare_send_request_register(param) {
    //公务员体检类型时，需要登记
    var content_arr = new Array();
    content_arr.push("[tjdj]");
    content_arr.push("request=TRUE");
    content_arr.push("success=");
    content_arr.push("error=");
    content_arr.push("cardno=" + param.cardno);
    content_arr.push("Yyksbm=" + param.department_no);
    content_arr.push("tjksmc=" + param.department_name);
    content_arr.push("bqbm00=" + param.disease_code);
    content_arr.push("bjtjxm=");
    //
    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}

//发送登记冲销请求
function medicare_send_request_cancel_register(param) {
    var content_arr = new Array();
    content_arr.push("[tjdjcx]");
    content_arr.push("request=TRUE");
    content_arr.push("cardno=" + param.cardno);
    content_arr.push("tjlsh0=" + param.medical_barcode);
    //
    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}

//发送收费请求
function medicare_send_request_charge(param) {
    var content_arr = new Array();
    content_arr.push("[tjdjsk]");
    content_arr.push("request=TRUE");
    content_arr.push("sfrq00=" + param.date);
    content_arr.push("Bqbm00=" + param.disease_code);
    content_arr.push("Yyksbm=" + param.department_no);
    //
    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}


//发送收费明细请求
function medicare_send_request_charge_detail(param) {
    var content_arr = new Array();
    content_arr.push("[tjsf]");
    content_arr.push("request=TRUE");
    content_arr.push("success=");
    content_arr.push("error=");
    content_arr.push("cardno=" + param.cardno);
    content_arr.push("tjlsh0=" + param.medical_barcode);
    content_arr.push("Yyksbm=" + param.department_no);
    content_arr.push("tjksmc=" + param.department_name);
    content_arr.push("bqbm00=" + param.disease_code);
    content_arr.push("bqbmmc=" + param.disease_name);
    //收费项目数
    content_arr.push("cfxms0=" + param.item_num);
    //是否银行支出
    content_arr.push("sfyhzc=" + param.is_bank_pay);
    //日期
    content_arr.push("Sfrq00=" + param.date);
    //各个发票项目费用：医保和非医保
    //收费次数，指同一挂号号(住院号)下的第X次收费(20090209新增参数)；对药店而言指的是该参保人当日在本药店收费的第几次收费（必填）
    content_arr.push("Bcsfcs=" + param.current_count);

    //医保费用细节
    content_arr.push("[yb0000]");
    content_arr.push(param.medical_pay_detail);
    //非医保费用细节
    content_arr.push("[fyb000]");
    content_arr.push(param.not_medical_pay_detail);
    //个人医保费用支付
    content_arr.push("[ybgr00]");
    content_arr.push(param.medical_personal_pay_detail);
    //处方明细
    content_arr.push("[tjsfmx]");
    content_arr.push(param.prescription_detail);

    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}

//发送收费冲销请求
function medicare_send_request_cancel_charge(param) {
    var content_arr = new Array();
    content_arr.push("[tjsfcx]");
    content_arr.push("request=TRUE");
    content_arr.push("cardno=" + param.cardno);
    //TODO:冲销单据号
    content_arr.push("cxdjh0=" + param.cxdjh0);
    //
    var content = content_arr.join("\r\n");
    api_medicare_send_request(content, param.respond_url);
}